package com.pfsoft.grpcserver.grpc.impl;

import com.google.protobuf.Empty;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.pfsoft.grpc.csv.api.CsvDataServiceGrpc;
import com.pfsoft.grpc.csv.api.DataInfo;
import com.pfsoft.grpcserver.domain.CsvDataEntity;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @author pengfei
 * @date 2022年07月19日 16:38
 */
@Slf4j
@GrpcService
@Service
public class CsvDataGrpc extends CsvDataServiceGrpc.CsvDataServiceImplBase {
    @Override
    public void getCsvData(Empty request, StreamObserver<DataInfo> responseObserver) {

        final ServerCallStreamObserver<DataInfo> scso =
                (ServerCallStreamObserver<DataInfo>) responseObserver;
        File file = null;
        CSVReader reader = null;
        try {
            file = ResourceUtils.getFile("classpath:static/test.csv");
            reader = new CSVReader(new FileReader(file));
//            测试整个文件读取
//            List myEntries = reader.readAll();
//            log.info("读取了【{}】多少条：",myEntries.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        CSVReader finalReader = reader;
        Runnable drain = new Runnable() {
            @Override
            public void run() {
                try {
                    String[] nextLine;
                    while ((nextLine = finalReader.readNext()) != null && scso.isReady()) {
                        if (!nextLine[0].equals("ID")) {  //首行跳过
                            DataInfo.Builder builder = DataInfo.newBuilder();
                            DataInfo dataInfo = builder.setId(Long.parseLong(nextLine[0])).setDiagnosis(Integer.parseInt(nextLine[1])).setRadiusMean(Double.parseDouble(nextLine[2])).setTextureMean(Double.parseDouble(nextLine[3])).build();
                            scso.onNext(dataInfo);
                        }
                    }
                    if(nextLine==null){
                        // 结束输出
                        scso.onCompleted();
                    }
                } catch (Exception ex) {
                    log.error("读取发生异常", ex);
                }
            }
        };
        scso.setOnReadyHandler(drain);
        drain.run();
    }



}
